package com.hebtu.helper.common.utils;

import com.hebtu.helper.common.constants.LoginMessage;
import com.hebtu.helper.common.exception.HelperException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.interfaces.RSAPublicKey;

/**
 * 针对正方教务的爬虫
 * @author YKF
 * @date 2019/6/18 20:52
 */
public class MyHttp {

    /**
     * Http客户端
     */
    private CloseableHttpClient myHttpClient;

    /**
     * 记录cookie
     */
    private String myCookie;

    /**
     * 记录正方教务系统页面表单的csrftoken的值
     */
    private String csrftoken;


    /**
     * 初始化,主要用于收集cookie
     */
    public MyHttp() {
        myHttpClient=HttpClients.createDefault();
        String url=LoginMessage.LOGIN_URL;
        try {
            HttpGet httpGet=new HttpGet(url);
            CloseableHttpResponse response=myHttpClient.execute(httpGet);//提交请求获得响应
            myCookie=response.getFirstHeader("Set-Cookie").getValue();//获取cookie
            StringBuffer sb=sendGetRequest(url);	//发送访问请求并获得响应页面
            csrftoken=HtmlTools.findCsrftoken(sb.toString()); //提取页面表单中的csrftoken的值

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Get请求
     * @param url 请求路径
     * @return
     */
    public StringBuffer sendGetRequest(String url) {
        StringBuffer html=new StringBuffer();
        InputStream in=null;
        HttpGet httpGet=new HttpGet(url);
        try {
            httpGet.setHeader("Cookie", myCookie);//设置cookie
            CloseableHttpResponse response=myHttpClient.execute(httpGet);//提交请求获得响应
            in=response.getEntity().getContent();
            //获取响应内容
            if(in!=null){
                int len=-1;
                byte[] data=new byte[1024];
                while((len=in.read(data))!=-1){
                    String s=new String(data,0,len,"UTF-8");
                    html.append(s);
                }
            }
            in=null;
        } catch (Exception e) {
            throw new HelperException("爬虫出错，请联系师大小助手管理员");
        }finally{
            try {
                if(in!=null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return html;
    }

    /**
     * post请求
     * @param url 请求路径
     * @param entity 请求参数实体
     * @return
     */
    public StringBuffer sendPostRequest(String url, UrlEncodedFormEntity entity) {
        StringBuffer html=new StringBuffer();
        HttpPost httpPost=new HttpPost(url);
        InputStream in=null;
        try {
            httpPost.setHeader("Cookie", myCookie);	//设置cookie
            httpPost.setEntity(entity);//设置请求参数
            CloseableHttpResponse response=myHttpClient.execute(httpPost);//提交请求
            in=response.getEntity().getContent();//获得响应流对象

            //获取响应内容
            int len=-1;
            byte[] data=new byte[1024];
            while((len=in.read(data))!=-1){
                String s=new String(data,0,len,"UTF-8");
                html.append(s);
            }
        } catch (Exception e) {
            throw new  HelperException("爬虫出错，请联系师大小助手管理员");
        }finally{
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return html;
    }

    /**
     * 获取登陆密匙
     * @return
     */
    public StringBuffer getPublicKey(){
        StringBuffer keyCont=new StringBuffer();
        HttpPost httpPost=new HttpPost(LoginMessage.LOGIN_PASS_URL);
        InputStream in=null;
        try {
            httpPost.setHeader("Cookie", myCookie);	//设置cookie
            CloseableHttpResponse response=myHttpClient.execute(httpPost);//提交请求
            in=response.getEntity().getContent();//获得响应流对象
            //获取响应内容
            int len=-1;
            byte[] data=new byte[1024];
            while((len=in.read(data))!=-1){
                String s=new String(data,0,len,"UTF-8");
                keyCont.append(s);
            }
        } catch (Exception e) {
            throw new HelperException("获取登陆密匙失败");
        }finally{
            try {
                if(in!=null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return keyCont;
    }

    /**
     * 密码加密
     * @param password  明文密码
     * @param privateKey 密匙
     * @return
     */
    public String getPasswordJson(String password,StringBuffer privateKey) {
        int end=privateKey.length();
        String modulus = privateKey.substring(12,end-20);
        String hex =  new BigInteger(Base64Tohex.b64tohex(modulus), 16).toString();
        String m =  new BigInteger(Base64Tohex.b64tohex("AQAB"), 16).toString();

        RSAPublicKey rsaPublicKey = Base64Tohex.getPublicKey(hex, m);
        String pwd = null;
        try {
            pwd = Base64Tohex.encryptByPublicKey(password, rsaPublicKey);
            pwd = Base64Tohex.hex2b64(pwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pwd;
    }


    public String getCsrftoken() {
        return csrftoken;
    }
}
